package com.price.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;

import androidx.core.app.ActivityCompat;


//基站定位
public class TelephonyUtils {


    public static TelephonyData getData(Context context) {
        TelephonyData data = new TelephonyData();

        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String operator = telephonyManager.getNetworkOperator();
        if (operator.length() > 3) {
            String mcc = operator.substring(0, 3);
            String mnc = operator.substring(3);

            data.setMCC(mcc);
            data.setMNC(mnc);
        }else {
            return null;
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return null;
        }
        int cid = 0;
        int lac = 0;
        if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {

            CdmaCellLocation cdmaCellLocation = (CdmaCellLocation)
                    telephonyManager.getCellLocation();
            cid = cdmaCellLocation.getBaseStationId(); //获取cdma基站识别标号 BID
            lac = cdmaCellLocation.getNetworkId(); //获取cdma网络编号NID
            int sid = cdmaCellLocation.getSystemId(); //用谷歌API的话cdma网络的mnc要用这个getSystemId()取得→SID
        }else{
            GsmCellLocation gsmCellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
            if(gsmCellLocation!=null) {
                cid = gsmCellLocation.getCid(); //获取gsm基站识别标号
                lac = gsmCellLocation.getLac(); //获取gsm网络编号
            }else {
                return null;
            }
        }

        data.setCID(String.valueOf(cid));
        data.setLAC(String.valueOf(lac));

        return data;
    }



}
